package com.cicdi.core.util;

import com.alaya.contracts.ppos.NodeContract;
import com.alaya.parameters.NetworkParameters;
import com.alaya.protocol.Web3j;
import com.alaya.protocol.core.DefaultBlockParameterName;
import com.alaya.protocol.http.HttpService;
import com.alaya.utils.Convert;
import lombok.extern.slf4j.Slf4j;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;

import java.awt.*;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * 节点类工具
 *
 * @author haypo
 * @date 2020/12/2
 */
@Slf4j
public class NodeUtil {

    public static boolean testNode(String nodeUrl) throws Exception {
        Web3j web3j = Web3j.build(new HttpService(nodeUrl));
        BigInteger number = web3j.platonGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock().getNumber();
        return number.longValue() >= 0;
    }

    /**
     * 生成节点排名的3d柱状图并保存为png格式
     *
     * @throws Exception io异常
     */
    public static void genNodeRankPicture() throws Exception {
        NodeContract nc = NodeContract.load(Web3j.build(new HttpService(Common.NODE_URL)), NetworkParameters.CurrentNetwork.getChainId());
        DefaultCategoryDataset dpd = new DefaultCategoryDataset();
        nc.getCandidateList().send().getData().subList(0, 101).forEach(
                s -> {
                    BigDecimal atp = Convert.fromVon(new BigDecimal(s.getDelegateTotal()), Convert.Unit.ATP);
                    System.out.println(s.getNodeName() + "\t" + atp);
                    dpd.addValue(atp, s.getNodeName(), "node name");
                }
        );

        JFreeChart chart = ChartFactory.createBarChart3D(
                //图表标题
                "节点委托量排名",
                //横轴标题
                "节点名称",
                //纵轴标题
                "委托量",
                //数据集合
                dpd,
                //图表方向
                PlotOrientation.VERTICAL,
                //是否显示图例标识
                true,
                //是否显示tooltips
                false,
                //是否支持超链接
                false);
        //设置Legend
        LegendTitle legend = chart.getLegend(0);
        legend.setItemFont(new Font("宋体", Font.BOLD, 14));
        //图片是文件格式的，故要用到FileOutputStream用来输出。
        OutputStream os = new FileOutputStream("节点委托量排名.png");
        //使用一个面向application的工具类，将chart转换成png格式的图片。第3个参数是宽度，第4个参数是高度。
        ChartUtilities.writeChartAsPNG(os, chart, 2240, 1400);

        os.close();//关闭输出流
    }
}
